package guiclient;

import java.util.List;

public class ClientMessageHandler {

    public static boolean answerAuthClient(String message)
            throws AuthClientException {
        String[] splitCommand = message.split(" ", 2);
        if (splitCommand.length < 1) {
            return false;
        }
        String command = splitCommand[0];
        if (MessagePrefix.AUTHOK.equalsString(command)) {
            return true;
        } else if (MessagePrefix.ERRAUTH.equalsString(command)) {
            String error = splitCommand[1];
            throw new AuthClientException(error);
        }
        return false;
    }

    public static void sendMessage(String message, Client client) {
        client.sendMessage(message);
    }

    public static long answerOrderClient(String message)
            throws AddOrderException {
        String[] splitCommand = message.split(" ", 2);
        if (splitCommand.length < 1) {
            return -1;
        }
        String command = splitCommand[0];
        if (MessagePrefix.ADDED.equalsString(command)) {
            String orderIdString = splitCommand[1];
            long orderId = Long.parseLong(orderIdString);
            return orderId;
        } else if (MessagePrefix.ERRADD.equalsString(command)) {
            String error = splitCommand[1];
            throw new AddOrderException(error);
        }
        return -1;
    }

    public static boolean handleServerMessage(String message, List<OrderTableBean> orderTableBeen) {
        String[] splitCommand = message.split(" ", 3);
        if (splitCommand.length < 3) {
            return  false;
        }
        String command = splitCommand[0];
        if (MessagePrefix.FILLED.equalsString(command)) {
            long id = Long.parseLong(splitCommand[1]);
            int rem = Integer.parseInt(splitCommand[2]);
            for (OrderTableBean been: orderTableBeen) {
                if (been.getId() == id) {
                    been.setRemainderSize(rem);
                }
            }
            return true;
        }
        return false;
    }
}
